#include <stdio.h>
#include "catalog.h"
#include "order.h"

#define PS1 "> "
#define GOODBYE_MESG "Goodbye\n"
#define CATALOG_PATH "catalog.bin"
#define ORDER_PATH "order.txt"

void command_addition(const char *);
void command_article(const char *);
void command_order(const char *);
void help();

int main(void)
{
    char *line;
    size_t n_chars = 0;
    catalog_read(CATALOG_PATH);
    order_read(ORDER_PATH);

    while(1)
    {
        puts(PS1);
        int n_read = getline(line, &n_chars, stdin);
        if(n_read == -1)
        {
            break;
        }
        switch(*line)
        {
            case 'q':
                goto free;
            case 'c':
                command_article(line);
                break;
            case 'p':
                command_order(line);
                break;
            case 'f':
                command_addition(line);
                break;
            default:
                puts("Syntax error: command not found\n");
                help();
        }
    }

    if(errno)
    {
        perror(NULL);
        fprintf(stderr, "", );
    }


free:
    free(line);
    catalog_free();
    order_free();
    puts(GOODBYE_MESG);
    return 0;
}


void help()
{
    const char mesg[] =
        "COMANDOS:\n"
        "q:\tsalir\n"
        "f:\tfactura\n"
        "c:\nCOMANDOS DEL CATÁLOGO\n"
        "\ta: añadir al catálogo\n"
        "\tl: listar el catálogo\n"
        "\ts: guardar el catálogo\n"
        "p:\tCOMANDOS DE PEDIDO\n"
        "\tn: nuevo pedido\n"
        "\ta: añadir elemento al pedido\n"
        "\tr: leer elemento\n"
        "\tl: listar el pedido\n"
        "\ts: guardar el pedido\n";
    printf("%s", mesg);
}

void command_article(const char *cmd)
{
    char subcommand = *(cmd + 1);
    switch(subcommand)
    {
        case 'a':
            char *article_str = strtok(cmd, ' ');
            catalog_add(catalog_parse(article));
            break;
        case 'l':
            for(Article *p = catalog; p; p = p->next)
                printf("%s %s %f", p->code, p->denom, p->price);
            break;
        case 's':
            catalog_save(CATALOG_PATH);
            break;
        default:
            puts("Syntax error: command not found\n");
            help();
    }
}

void command_order(const char *cmd)
{
    char subcommand = *(cmd + 1);
    switch(subcommand)
    {
        case 'n':
            order_free();
            break;
        case 'a':
            char *order_str = strtok(cmd, ' ');
            order_add(order_parse(order_str));
            break;
        case 'r':
            break;
        case 'l':
            int i = 1;
            for(Item *p = order; p; p = p->next, ++i)
                printf("%d: %s %lu\n", i, p->code, p->num_units);
            break;
        case 's':
            order_save(ORDER_PATH);
            break;
    }
}
